package handlers

import (
	"encoding/json"
	"net/http"
	"strings"
	"werewolf/core"

	"golang.org/x/exp/rand"
)

func RoomHandler(w http.ResponseWriter, r *http.Request) { // 获取房间信息和处理玩家角色
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	room := r.URL.Query().Get("room")
	user := r.URL.Query().Get("user")

	response := map[string]interface{}{
		"selfRole":   -2,
		"playerNo":   8, //游戏人数
		"roleList":   []string{},
		"No":         0,
		"playerList": map[int]string{},
		"creator":    "",
	}

	handle, err := core.Connection()
	if err != nil {
		http.Error(w, "Connection failed: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer handle.Close()

	var flagHasGame bool
	var setRoles string
	var werewolves, folks int
	var creator string

	gameInfo, err := handle.Query("SELECT PlayerNo,Role,Werewolf,Folk,Creator FROM Game WHERE RmNo=?", room)
	if err != nil {
		http.Error(w, "Error fetching game info: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer gameInfo.Close()

	for gameInfo.Next() {
		var playerNo int
		err := gameInfo.Scan(&playerNo, &setRoles, &werewolves, &folks, &creator)
		if err != nil {
			http.Error(w, "Error scanning game info: "+err.Error(), http.StatusInternalServerError)
			return
		}
		response["playerNo"] = playerNo //游戏人数
		response["creator"] = creator
		flagHasGame = true
	}

	if !flagHasGame {
		json.NewEncoder(w).Encode(response)
		return
	} //如果没有找到对应的房间

	var roles []string
	if setRoles != "" {
		roles = strings.Split(setRoles, ";")
	}

	for i := 0; i < werewolves; i++ {
		roles = append(roles, "w")
	}
	for i := 0; i < folks; i++ {
		roles = append(roles, "f")
	} //加入普通狼和平民
	response["roleList"] = roles //角色名单，每个位置存放着一个对应的role，返回到前端

	//
	playerInfo, err := handle.Query("SELECT Role, No FROM Player WHERE RmNo=? AND Username=?", room, user)
	if err != nil {
		http.Error(w, "Error fetching player info: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer playerInfo.Close()

	for playerInfo.Next() {
		var selfRole, playerNo int
		err := playerInfo.Scan(&selfRole, &playerNo)
		if err != nil {
			http.Error(w, "Error scanning player info: "+err.Error(), http.StatusInternalServerError)
			return
		}
		response["selfRole"] = selfRole //
		response["No"] = playerNo       //
	}

	//加入ai玩家分配角色，在create中完成。

	if response["selfRole"].(int) == -2 {
		var role []int
		var maxNo int

		hasRole, err := handle.Query("SELECT Role, No FROM Player WHERE RmNo=?", room)
		if err != nil {

			http.Error(w, "Error fetching roles: "+err.Error(), http.StatusInternalServerError)
			return
		}
		defer hasRole.Close()

		for hasRole.Next() {
			var r, no int //代表角色和玩家编号
			err := hasRole.Scan(&r, &no)
			if err != nil {
				http.Error(w, "Error scanning roles: "+err.Error(), http.StatusInternalServerError)
				return
			}
			role = append(role, r)
			if no > maxNo {
				maxNo = no
			}
		}

		if len(role) >= response["playerNo"].(int) {
			response["selfRole"] = -1 //房间已满
		} else {
			newRole := rand.Intn(response["playerNo"].(int)) + 1
			for contains(role, newRole) {
				newRole = rand.Intn(response["playerNo"].(int)) + 1
			} //确保分配
			maxNo++
			_, err = handle.Exec("INSERT INTO Player VALUES (?, '', ?, ?, ?, 1, 0)", user, room, newRole, maxNo)
			if err != nil {
				_, err = handle.Exec("UPDATE Player SET Role=?, No=?, Survival=1, RmNo=?, Vote = 0  WHERE Username=?  ", newRole, maxNo, room, user)
				if err != nil {
					http.Error(w, "Error updating player: "+err.Error(), http.StatusInternalServerError)
					return
				}
			}

			response["selfRole"] = newRole
			response["No"] = maxNo
		}
	}

	listInfo, err := handle.Query("SELECT Username, No FROM Player WHERE RmNo=?", room)
	if err != nil {
		http.Error(w, "Error fetching player list: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer listInfo.Close()

	for listInfo.Next() {
		var username string
		var no int
		err := listInfo.Scan(&username, &no)
		if err != nil {
			http.Error(w, "Error scanning player list: "+err.Error(), http.StatusInternalServerError)
			return
		}
		response["playerList"].(map[int]string)[no] = username
	} //返回玩家名单


	json.NewEncoder(w).Encode(response)
}
